package com.vf.admin.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppUserDao;
import com.vf.admin.client.dto.UserAuthDto;
import com.vf.admin.client.dto.UserDto;
import com.vf.admin.client.dto.VoiceSignatureDto;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.*;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.vf.admin.common.Constants.guizuCacheMap;
import static com.vf.admin.utils.StringEx.isNull;
import static com.vf.admin.utils.ConstellationUtil.removeSfm;

/**
 * 用户个人信息  --黑哲
 */
@Controller
@RequestMapping("/app/usermessage")
public class AppUserMessageController extends ClientBaseController {

    @Autowired
    AppUserDao appUserDao;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppUserDressupService appUserDressupService;
    @Autowired
    AppRealNameService appRealNameService;
    @Autowired
    private AppGuanZhuAndFenSiController appGuanZhuAndFenSiController;
    @Autowired
    private AppMountsService appMountsService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private AppVisitorService appVisitorService;
    @Autowired
    private AppAuthUserService appAuthUserService;
    @Autowired
    AppFollowService appFollowService;
    @Autowired
    private AppHeadwearService headwearService;

    /**
     * 获取个人信息
     *
     * @return
     */
    @RequestMapping("/getMessage")
    @ResponseBody
    public Result getMessage() {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            if (userId == null) return errorJSON("请登录");
            AppUser user = appUserService.get(userId);
            //数据迁移至dto
            UserDto ud = new UserDto();
            BeanUtils.copyProperties(user, ud);
            //生日格式转换，只显示年月日
            if (ObjectUtil.isNotEmpty(user.getBirthday())){
                ud.setBirthday(removeSfm(user.getBirthday()));
            }

            //判断用户是否是贵族
            if (user.getIsguizu() == 1) {
                //根据贵族id  获取贵族图标
                String medal = guizuCacheMap.get(user.getNobleid());
                ud.setMedal(medal);
            } else {
                ud.setMedal("");
            }
//            Integer isReal = appAuthUserService.infoByUserAndName(userId, ClientConstants.UserAuth.REAL_AUTH);
            //  Boolean realAuth = ObjectUtil.isNotNull(isReal) && isReal.equals(2);

            AppAuthUser appNameAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.REAL_NAME_AUTH);
            Boolean realNameAuth =
                    ObjectUtil.isNotNull(appNameAuthUser)
                            && ObjectUtil.isNotNull(appNameAuthUser.getStatus())
                            && appNameAuthUser.getStatus().equals(2);

            if (realNameAuth) {
                ud.setIsReal(2);
            } else {
                ud.setIsReal(0);
            }

            AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.REAL_AUTH);
            if (appAuthUser != null) {
                ud.setShipinstate(appAuthUser.getStatus());
            } else {
                ud.setShipinstate(0);
            }
            //获取用户的默认头饰
            AppUserDressup toushi = appUserDressupService.getUserid(user.getId(), 2);
            //判断实体类是否为空？true 为空；反之则有值，取其头饰图片
            String headWear = StringUtils.isEmpty(toushi) ? "" : toushi.getGoodpic();
            ud.setHeadWear(headWear);
            if (toushi != null) {
                AppHeadwear appHeadwear = headwearService.get(toushi.getMountsid());
                if (appHeadwear != null) {
                    ud.setToushiSvga(appHeadwear.getSvgaAddress());
                }
            }
            //获取用户的默认坐骑
            AppUserDressup zuoqi = appUserDressupService.getUserid(user.getId(), 1);
            //判断实体类是否为空？true 为空；反之则有值，取其坐骑图片
            String zuoqi1 = StringUtils.isEmpty(zuoqi) ? "" : zuoqi.getGoodpic();
            ud.setZuoqi(zuoqi1);
            List<String> bqList = new ArrayList<>();
            //判断用户是否添加标签
            if (!isNull(ud.getBiaoqianname())) {
                //切割
                String[] bq = ud.getBiaoqianname().split(",");
                bqList = Arrays.asList(bq);
            }
            ud.setBiaoqianList(bqList);
            ud.setArea(user.getArea());
            ud.setFirends(appGuanZhuAndFenSiController.getFriendsNumber(userId).size());

            //获取粉丝数
            Map<String, Object> mapOne = new HashMap<>();
            mapOne.put("userid", userId);
            List<AppFollow> one = appFollowService.findByListAll(mapOne);
            ud.setFansnumall(one.size());
            //获取关注数
            Map<String, Object> mapTwo = new HashMap<>();
            mapTwo.put("followeduserid", userId);
            List<AppFollow> listOne = appFollowService.findByListAll(mapTwo);
            ud.setGuanzhu(listOne.size());

            //访客数量
            int visitorCount = appVisitorService.visitorCount(userId);
            ud.setVisitorCount(visitorCount);


            ud.setCharmvalue(new Long(user.getCharmvalue()).intValue());
            ud.setTengxuncode(user.getTengxuncode());

            //语音签名内容 时长 点赞数 是否点赞
            VoiceSignatureDto signatureDto = appAuthUserService.infoVoiceSignature(userId, userId);
            ud.setSignatureDto(signatureDto);
            //认证信息
            List<UserAuthDto> userAuthDtoList = appAuthUserService.infoByUser(userId);
            ud.setUserAuthDtoList(userAuthDtoList);

            Map<String, Object> vipMap = appUserService.isVipMap(userId);
            ud.setVipMap(vipMap);

            //日活跃
            //判断是否存在
            String key = String.format(RedisKeys.activeKey, userId);
            Object  object = redisUtil.get(key);
            if (ObjectUtil.isEmpty(object)){
                //计算当天剩余时间秒
                DateTime dateTime = new DateTime().millisOfDay().withMaximumValue();
                long count = new Duration(new DateTime(), dateTime).getStandardSeconds();

                String keys = String.format(RedisKeys.activeKey, userId);
                redisUtil.set(keys ,userId,count);
            }
            System.out.println("------------执行个人信息接口------------");
//
//            Set<String> keys = redisUtil.keys(RedisKeys.active + "*");
//            System.out.println("日活跃度" + keys.size());


            return sucessJSON(ud);
        } catch (Exception e) {
            e.printStackTrace();
            return errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 获取用户坐骑
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getUserMount")
    @ResponseBody
    public Result getUserMount(Integer userId) {
        //获取用户的默认坐骑
        String mountImage = "";
        AppUserDressup mount = appUserDressupService.getUserid(userId, 1);
        //判断实体类是否为空？true 为空；反之则有值，取其坐骑图片
        if (Objects.isNull(mount)) {
            mountImage = "";
        } else {
            AppMounts appMounts = appMountsService.get(mount.getMountsid());
            mountImage = appMounts.getSvgaaddress();
        }
        return sucessJSON(mountImage, "成功");
    }

}
